package com.jichangxiu.framework.security.encoder;

import com.jichangxiu.common.exception.FrameworkException;
import com.jichangxiu.common.utils.RsaUtils;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.security.PrivateKey;

/**
 * PasswordEncoder:
 *
 * @author Jcx
 * @create 2023-04-04 11:13
 */
@Slf4j
@Component
@NoArgsConstructor
public class PasswordEncoder extends BCryptPasswordEncoder {

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        // 接收到的前端的密码
        String pwd = rawPassword.toString();
        // 进行rsa解密
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey("private.key");
            pwd = RsaUtils.decrypt(pwd, privateKey);
        } catch (Exception e) {
            throw FrameworkException.build("Rsa 解密异常", e);
        }
        if (encodedPassword != null && encodedPassword.length() != 0) {
            return BCrypt.checkpw(pwd, encodedPassword);
        } else {
            return false;
        }
    }

}
